const { request } = require('../../../../utils/request');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showStationSelector: false,
    stationIndex: 0,
    loginType:'', // 2站点管理 3企业管理
    stationArray:[],
    userActive: '0',
    minDate: new Date('2021/12/01').getTime(),
    maxDate: new Date().getTime(),
    queryOrder: {
      startId: '',
      orderStatus: 1,
      date: '',
      minDate: '',
      maxDate: '',
      minMoney: 0,
      maxMoney: '',
      sIndex:''
    },
    queryDone: {
      startId: '',
      orderStatus: 2,
      date: '',
      minDate: '',
      maxDate: '',
      minMoney: 0,
      maxMoney: '',
      sIndex:''
    },
    selectMode: '',
    selectTimeStr: '按时间筛选',
    showTimeSelector: false,
    showMoneySelector: false,
    minMoney1: '',
    maxMoney1: '',
    minMoney2: '',
    maxMoney2: '',
    orderTotal: 0,
    orderList: [],
    orderEnd: false,
    doneTotal: 0,
    doneList: [],
    doneEnd: false,
    userInfo: {
      userName: '',
      nickName: '',
      userAvatar: '',
      stationIndex: '',
      stationName: ''
    },
    showStationConfim: false,
    showStationErr: false,
    showSubmitInfo: false,
    total:0,
    total2:0
    // 2022.2.21 微信回收open-type 能力
    // canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName'),
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initData()
    this.setData({
      loginType: wx.getStorageSync('userInfo').loginType
    })

    wx.setNavigationBarTitle({
      title: '订单列表'
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // console.log('show')
  },
  initData() {
    this.setData({
      ['queryOrder.startId']: '',
      ['queryDone.startId']: '',
      orderList: [],
      doneList: [],
      orderEnd: false,
      doneEnd: false,
    })
    this.getStations()
    this.fetchOrderCount()
    this.fetchOrderList()
    if (wx.getStorageSync('tempTabId')) {
      this.tabChange(wx.getStorageSync('tempTabId'), 'fresh')
      wx.removeStorageSync('tempTabId')
    }
  },
  /**
   * 获取站点列表
   */
  getStations(){
    request('/smsk/wechat/orderinfo/stations', 'GET',{companyId:wx.getStorageSync('userInfo').companyId}).then(res => {
      console.log(res.data)
      if (res.data.code == 0) {
        res.data.data.unshift({id:'',stationName:'全部'})
        this.setData({
          stationArray:res.data.data
        })
      } else {
        console.log(res)
      }
    })
  },
  /**
   * 选择站点
   * @param {*} e 
   */
  stationPick(e){
    this.setData({
      ['queryOrder.sIndex']:e.detail.value,
      ['queryOrder.stationId']:this.data.stationArray[e.detail.value].id
    })
    this.setData({ ['queryOrder.startId']: '', orderList: [], orderEnd: false })
    this.fetchOrderList();
  },
  /**
   * 选择站点
   * @param {*} e 
   */
  stationPick_2(e){
    this.setData({
      ['queryDone.sIndex']:e.detail.value,
      ['queryDone.stationId']:this.data.stationArray[e.detail.value].id
    })
    this.setData({ ['queryDone.startId']: '', doneList: [], doneEnd: false })
    this.fetchDoneList();
  },
 

  /**
   * 获取运行中订单列表
   */
  fetchOrderList() {
    if (this.data.orderEnd) {
      return
    }
    request('/smsk/wechat/orderinfo/list', 'GET', this.data.queryOrder).then(res => {
      // console.log(res.data)
      if (res.data.code == 0) {
        var tempList = this.data.orderList
        res.data.data.forEach(item => {
          tempList.push(item)
        })
        if (tempList.length > 0) {
          this.setData({
            orderList: tempList,
            ['queryOrder.startId']: tempList[tempList.length - 1].id,
            orderEnd: tempList.length < 10 ? true : false
          })
        }
        //计算总金额
        let temMoney = 0;
        for(let i = 0; i < tempList.length ; i++){
          temMoney += tempList[i].totalAmount
        }
        this.setData({
          total:temMoney
        })
      } else {
        console.log(res)
      }
    })
  },
  /**
   * 获取已完成订单列表
   */
  fetchDoneList() {
    if (this.data.doneEnd) {
      return
    }
    request('/smsk/wechat/orderinfo/list', 'GET', this.data.queryDone).then(res => {
      // console.log(res.data)
      if (res.data.code == 0) {
        var tempList = this.data.doneList
        res.data.data.forEach(item => {
          tempList.push(item)
        })
        if (tempList.length > 0) {
          this.setData({
            doneList: tempList,
            ['queryDone.startId']: tempList[tempList.length - 1].id
          })
        }
        //计算总金额
        let temMoney = 0;
        for(let i = 0; i < tempList.length ; i++){
          temMoney += tempList[i].totalAmount
        }
        this.setData({
          total2:temMoney
        })
      } else {
        console.log(res)
      }
    })
  },
  /**
   * 获取订单数
   */
  fetchOrderCount() {
    request('/smsk/wechat/orderinfo/total', 'GET').then(res => {
      if (res.data.code === 0) {
        this.setData({
          orderTotal: res.data.data.runningCount,
          doneTotal: res.data.data.doneCount
        })
      } else {
        console.log(res)
      }
    })
  },
  /**
   * 展示日期选择器
   */
  selectTime(e) {
    // console.log(e.currentTarget.dataset.mode)
    this.setData({
      showTimeSelector: true,
      selectMode: e.currentTarget.dataset.mode
    })
  },
  /**
   * 关闭日期选择器
   */
  onCloseTime(e) {
    this.setData({
      showTimeSelector: false,
      selectMode: ''
    })
  },
  /**
   * 设置选择的日期
   */
  onConfirmTime(event) {
    const [start, end] = event.detail;
    this.setData({
      showTimeSelector: false,
      [this.data.selectMode + '.date']: `${this.formatDateMD(start)} - ${this.formatDateMD(end)}`,
      [this.data.selectMode + '.minDate']: `${this.formatDateYMD(start)}`,
      [this.data.selectMode + '.maxDate']: `${this.formatDateYMD(end)}`,
    });
    if (this.data.selectMode === 'queryOrder') {
      this.setData({ ['queryOrder.startId']: '', orderList: [], orderEnd: false })
      this.fetchOrderList()
    } else {
      this.setData({ ['queryDone.startId']: '', doneList: [], doneEnd: false })
      this.fetchDoneList()
    }
  },
  formatDateMD(date) {
    date = new Date(date);
    return `${date.getMonth() + 1}/${date.getDate()}`;
  },
  formatDateYMD(date) {
    date = new Date(date);
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  },
  /**
   * 清空日期筛选
   */
  cleanDate(e) {
    this.setData({
      [e.currentTarget.dataset.mode + '.date']: '',
      [e.currentTarget.dataset.mode + '.minDate']: '',
      [e.currentTarget.dataset.mode + '.maxDate']: '',
    })
    if (e.currentTarget.dataset.mode === 'queryOrder') {
      this.setData({ ['queryOrder.startId']: '', orderList: [], orderEnd: false })
      this.fetchOrderList()
    } else {
      this.setData({ ['queryDone.startId']: '', doneList: [], doneEnd: false })
      this.fetchDoneList()
    }
  },
  /**
   * 展示金额填写框
   */
  selectMoney(e) {
    this.setData({
      showMoneySelector: true,
      selectMode: e.currentTarget.dataset.mode
    })
  },
  /**
   * 关闭金额填写框
   */
  onCloseMoney() {
    this.setData({
      showMoneySelector: false,
      selectMode: ''
    })
  },
  /**
   * 清空填写金额
   */
  cleanMoney(e) {
    if (e.currentTarget.dataset.mode === 'queryOrder') {
      this.setData({
        minMoney1: '',
        maxMoney1: '',
        ['queryOrder.minMoney']: '',
        ['queryOrder.maxMoney']: '',
      })
      this.setData({ ['queryOrder.startId']: '', orderList: [], orderEnd: false })
      this.fetchOrderList()
    } else {
      this.setData({
        minMoney2: '',
        maxMoney2: '',
        ['queryDone.minMoney']: '',
        ['queryDone.maxMoney']: '',
      })
      this.setData({ ['queryDone.startId']: '', doneList: [], doneEnd: false })
      this.fetchDoneList()
    }
  },
  /**
   * 确认填写金额
   */
  onConfirmMoney(e) {
    let mode = this.data.selectMode
    this.setData({
      [this.data.selectMode + '.minMoney']: this.data.selectMode === 'queryOrder' ? this.data.minMoney1 : this.data.minMoney2,
      [this.data.selectMode + '.maxMoney']: this.data.selectMode === 'queryOrder' ? this.data.maxMoney1 : this.data.maxMoney2,
      showMoneySelector: false,
      selectMode: ''
    })
    // 刷新list
    if (mode === 'queryOrder') {
      this.setData({ ['queryOrder.startId']: '', orderList: [], orderEnd: false })
      this.fetchOrderList()
    } else {
      this.setData({ ['queryDone.startId']: '', doneList: [], doneEnd: false })
      this.fetchDoneList()
    }
  },
  userTabChange(e) {
    console.log(111)
    this.setData({
      userActive: e.currentTarget.id
    })
    if( e.currentTarget.id == 0){
      this.fetchOrderList()
    }else if( e.currentTarget.id == 1){
      this.fetchDoneList()
    }
  },
  fetchOrderDetail(e) {
    // console.log(e.currentTarget.id)
    wx.navigateTo({
      url: '/pages/cashService/operator/orderDetail/orderDetail?orderId=' + e.currentTarget.id,
    })
  },
  logout() {
    request('/smsk/wechat/auth/logout', 'POST').then(res => {
      console.log(res.data)
      if (res.data.code == 0) {
        wx.setStorageSync('userInfo', res.data.data)
        wx.setStorageSync('token', res.data.data.token)
        wx.redirectTo({
          url: '/pages/cashService/roleSelection/roleSelection',
        })
      } else {
        this.showToast(res.data.message)
      }
    })
  }
})